package org.carota.itext5;

import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.carota.pdf.PdfConfigurer;
import org.carota.pdf.PdfProcessor;

import java.nio.charset.StandardCharsets;

/**
 * @author : AnWen
 * @version :1.0
 * @email : anwen375@qq.com
 * @since : 2023-03-29 18:59
 */
@Slf4j
@NoArgsConstructor
public class EncryptConfigurer extends PdfConfigurer {

    private String userPassword;
    private String ownerPassword;
    private Integer permissions;

    public EncryptConfigurer(PdfProcessor processor) {
        super(processor);
    }

    public EncryptConfigurer userPassword(String password) {
        this.userPassword = password;
        return this;
    }

    public EncryptConfigurer ownerPassword(String password) {
        this.ownerPassword = password;
        return this;
    }

    public EncryptConfigurer permissions(int permissions) {
        this.permissions = permissions;
        return this;
    }


    /**
     * 加密
     */
    @Override
    public void execute() {
        PdfStamper stamper = processor.getStamper ();
        try {
            stamper.setEncryption (
                    userPassword == null ? null : userPassword.getBytes (StandardCharsets.UTF_8),
                    ownerPassword.getBytes (StandardCharsets.UTF_8),
                    permissions,
                    PdfWriter.ENCRYPTION_AES_256);
            getProcessor ().setOwnerPassword (ownerPassword);
        } catch (Exception e) {
            log.error ("加密异常: ", e);
            throw new RuntimeException ("加密PDF异常");
        }
    }

    /**
     * 校验参数
     */
    @Override
    protected void checkParams() {
        checkParams("加密",ownerPassword, "ownerPassword",permissions,"permissions");
    }



    @Override
    public int getOrder() {
        return 40;
    }
}
